package com.tbh.security3.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


/**
 * 从数据库查询用户名密码
 */
@Configuration
public class SecurityUserDetailsConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(getPassWordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 自定义编写的登录界面
        http.formLogin()
                // 登录页面设置
                .loginPage("/login.html")
                // 登录提交表单访问路径
                .loginProcessingUrl("/api/home/login")
                // 登录成功后跳转的路径
                .defaultSuccessUrl("/api/home/index").permitAll()
                // 设置哪些url请求不需要认证即可访问，
                .and().authorizeRequests()
                .antMatchers("/api/home/login", "/api/test/visit").permitAll()
                // 所有请求都需要认证访问，即需要验证用户名密码
                .anyRequest().authenticated()
                // 跨站请求伪造
                // 跨站请求伪造 是一种web攻击手段，通过向服务器发送伪造请求，进行恶意行为的攻击手段
                .and().csrf().disable();


    }

    @Bean
    PasswordEncoder getPassWordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
